<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Model;
use think\Request;
use think\facade\Cache;
use Zewail\Api\Facades\JWT;
use Zewail\Api\JWT\Factories\Code;

class Index extends Controller
{
    public function initialize()
    {
        error_reporting(5);
        //设置跨域头
        header('Access-Control-Allow-Origin: *');
        //token 验证登录信息是否有效
        $request = new Request();
        $g=$request->get();
        $p=$request->post();
        $token = '';
        (isset($g['token']) && !empty($g['token'])) and ($token = $g['token']);
        (isset($p['token']) && !empty($p['token'])) and ($token = $p['token']);
        if(empty($token)){
            js_code('
                    var str = localStorage.getItem("token");
                    if(str !=="" || str.length>0){
                        var preg = /(\?token=.*|\?.*)/i
                        var href = location.href.replace(preg,"");
                        location.href=(href+"?token="+localStorage.getItem("token")).replace(/[?]{2,}/g,"?");
                    }else{
                        location.href="/admin_login_out";
                    }   
               ');
        }
        $jwt = new \app\common\controller\publics\Jwt();
        if(!$jwt->is_token($g['token']) || empty(cookie('fwf_admin_name'))){
            $this->error('信息验证错误，请重新登录','/admin_login_out');
        }
    }

    public function index(Request $request)
    {

        $m_tree = self::get_menu();

        $this->assign('new_menu',$m_tree);
        $this->assign('title','首页');
        $arr = ['field_name'=>'','field_has'=>'','field_desc'=>'','checked'=>''];

        return self::fetch();
    }

    public function test(Code $code){
        $c=$code->encode(['key'=>'','pass_key'=>'','nbf'=>time()-1000,'exp'=>time()+1]);
        dump($c);
        dump($code->decode($c));

        $class = new \ReflectionClass('Zewail\Api\Facades\JWT');
        $methods = $class->getMethods();
        dump($methods);


        return dump(JWT::getToken());
    }

    public function token(){
        $code = new Code();
        $payload = [
           'iss'    =>'jwt_admin',  //该JWT的签发者
           'iat'    =>time(),  //签发时间
           'exp'    =>time()+15,  //过期时间
           'nbf'    =>time()+5,  //该时间之前不接收处理该Token
           'sub'    =>'www.admin.com',  //面向的用户
           'jti'    =>md5(uniqid('JWT').time())  //该Token唯一标识
        ];
        $menu = Db::table('qw_auth_rule')->select();

        $token = $code->encode($payload);
        dump($token);
        //@dump($code->get_config());
        $menu[] = $payload;
        $menu = $code->encode($menu);
        dump($menu);
        setcookie('menu_token',$menu,0,'/');
//        print_r("
//            <script type='text/javascript'>
//                localStorage.setItem('menu_token','$menu');
//                localStorage.setItem('user_token','$token');
//                //localStorage.menu_token='$menu';
//            </script>
//        ");
        @$this->LO([ 'menu_token'=>$menu,'user_token'=>$token,'test'=>'abc' ]);
    }

    public function cheke_token(Request $request){
        $t = $request->param('token');
        $g = $request->get();
        $p = $request->post();
        $code = new Code();
        if ($token = $code->verify_token($t)){
            dump("验证成功！");
        }
        else{
            dump("验证失败！");
        }
    }

    private function LO($key,$value=''){
        $str="";
        if(is_array($key)){
            foreach ($key as $k => $item) {
                $str.="localStorage.setItem('$k','$item');";
                //localStorage['$k']='$item';
            }
            $this->js_code($str);
        }
        else{
            $this->js_code("localStorage.setItem('$key','$value')");
        }
    }
    private function js_code($str){
        print_r("<script type='text/javascript'>$str</script>");
    }

    public function save(\app\common\controller\publics\Jwt $jwt){
//        $token = $jwt->encode(['abc'=>'cccc','dd'=>'cccsjdoijs']);
        $token = $jwt->create_token(60,['nbf'=>time(),'id'=>'11']);
         $d=$jwt->decode($token);
         dump(base64_encode('“”{}{}'));
         dump($a=$jwt->encode64('“”{}{}'));
         dump($jwt->decode64($a));dump(base64_decode($a));
         dump($token);
         dump($d);
         halt(serialize($d));

    }

    public function set_menu(){
        $menu = Db::table('fwf_menu')->where('menu_status','=',1)->where('menu_show','=',1)->order('menu_order','desc')->select();
        $GLOBALS['tree']['pid'] = 'menu_pid';
        $GLOBALS['tree']['id'] = 'menu_id';
        $m_tree = get_tree($menu);
        set_leval($m_tree,0);
        //Cache::set('menu',$m_tree);
        Cache::tag('menu')->set('menu',$m_tree);
    }
    public function get_menu(){
        //return Cache::get('menu');
        return Cache::tag('menu')->get('menu');
    }
    public function clear_cache(){
        //Cache::clear();
        Cache::clear('menu');
        self::set_menu();

        //前台的头部导航栏
        Cache::clear('home_');
        $this->success('清除缓存成功！',null,null,3);
    }

}
